package com.jic.member.controller.manage;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.enums.RedisKey;
import com.jic.enums.RedisTime;
import com.jic.member.entity.Member;
import com.jic.member.entity.MememberUser;
import com.jic.member.entity.SmsLog;
import com.jic.member.request.GetMemberInfoRequest;
import com.jic.member.request.GetMemberSettingPasswordByTokenRequest;
import com.jic.member.request.MemberRequest;
import com.jic.member.request.UpdateMemberPassWordByTokenRequest;
import com.jic.member.response.GetMemberInfoResponse;
import com.jic.member.response.GetMemberMobileByTokenResponse;
import com.jic.member.response.MemberRestResponse;
import com.jic.member.service.MememberUserService;
import com.jic.member.service.SmsLogService;
import com.jic.member.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;
import java.util.UUID;


/**
 * @author: MJ
 * @date: 2020-01-09
 * @remark: 会员信息服务
 */
@Slf4j
@SuppressWarnings("all")
@Api( tags = "H5-用户")
@RestController
@RequestMapping("/apiMember")
public class ApiMemberController {

    @Autowired
    RedisClientTemplate redisClientTemplate;

    @Resource
    MememberUserService mememberUserService;

    @Autowired
    SmsLogService smsLogService;


    @ApiOperation("根据token查询用户的积分余额")
    @ResponseBody
    @PostMapping("getMemberInfo")
    public RestResult<GetMemberInfoResponse> getMemberInfo(@RequestBody GetMemberInfoRequest getMemberInfoRequest) {
        String token = getMemberInfoRequest.getToken();
        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + token);
        MememberUser member = JSONArray.parseObject(memStr, MememberUser.class);
        MememberUser memberVo = mememberUserService.queryByPrimaryKey(member.getId());
        return RestResult.success(new GetMemberInfoResponse() {{
            setIntegration(memberVo.getIntegral());
        }});
    }

    @ApiOperation("根据token获取脱敏手机号")
    @ResponseBody
    @PostMapping("getMemberMobileByToken")
    public RestResult<GetMemberMobileByTokenResponse> getMemberMobileByToken(@RequestBody GetMemberInfoRequest getMemberMobileByTokenRequest) {
        String token = getMemberMobileByTokenRequest.getToken();
        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + token);
        if (StringUtils.isEmpty(memStr)) {
            return RestResult.error("4000", "登录失效");
        }
        Member member = JSONArray.parseObject(memStr, Member.class);
        MememberUser mememberUser = mememberUserService.queryByPrimaryKey(member.getId());
        Integer status = mememberUser.getStatus();
        if (status == 0) {
            return RestResult.error("9999", "当前账号已注销");
        }
        return RestResult.success(new GetMemberMobileByTokenResponse() {{
            setId(mememberUser.getId());
            setMobile(StringUtils.overlay(mememberUser.getPhone(), "****", 3, 7));
        }});
    }

    @ApiOperation("根据token查询用户是否设置过密码  true为已设置 false为未设置")
    @ResponseBody
    @PostMapping("getMemberSettingPasswordByToken")
    public RestResult<Boolean> getMemberSettingPasswordByToken(@RequestBody GetMemberSettingPasswordByTokenRequest getMer) {
        String token = getMer.getToken();
        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + token);
        if (StringUtils.isEmpty(memStr)) {
            return RestResult.error("4000", "登录失效");
        }
        Member member = JSONArray.parseObject(memStr, Member.class);
        MememberUser mememberUser = mememberUserService.queryByPrimaryKey(member.getId());
        Integer status = mememberUser.getStatus();
        if (status == 0) {
            return RestResult.error("9999", "当前账号已注销");
        }
        return RestResult.success(StringUtils.isNotEmpty(mememberUser.getPassword()));
    }

    @ApiOperation(value = "获取短信验证码")
    @ResponseBody
    @PostMapping("/getMessageCode")
    public RestResult<MemberRestResponse> getMessageCode(@RequestBody MemberRequest memberRequest) {
        try {
            String code = String.format("%04d", new Random().nextInt(9999));
            String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + memberRequest.getToken());
            Member member = JSONArray.parseObject(memStr, Member.class);
            if (memberRequest.getCodeType() == 0) {
                String phone = memberRequest.getMobile();
                if (StringUtils.isEmpty(phone)) {
                    throw new Exception("手机号为空");
                }
                redisClientTemplate.setex(RedisKey.LOGIN_MESSAGE_KEY_.getName() + phone, Integer.valueOf(RedisTime.MESSAGE_TIME.getName().toString()), code);
            } else if (memberRequest.getCodeType() == 1) {
                if (member == null) {
                    return RestResult.error("4000", "登录失效");
                }
                redisClientTemplate.setex(RedisKey.CHECK_MOBILE_MESSAGE_KEY_.getName() + member.getMobile(), Integer.valueOf(RedisTime.MESSAGE_TIME.getName().toString()), code);
            } else if (memberRequest.getCodeType() == 2) {
                if (member == null) {
                    return RestResult.error("4000", "登录失效");
                }
                redisClientTemplate.setex(RedisKey.UPDATE_PASSWORD_MESSAGE_KEY_.getName() + member.getMobile(), Integer.valueOf(RedisTime.MESSAGE_TIME.getName().toString()), code);
            } else if (memberRequest.getCodeType() == 3) {
                if (member == null) {
                    return RestResult.error("4000", "登录失效");
                }
                if (memberRequest.getMobile().equals(member.getMobile())) {
                    throw new Exception("新号码不能和老号码相同");
                }
                redisClientTemplate.setex(RedisKey.UPDATE_MOBILE_MESSAGE_KEY_.getName() + memberRequest.getMobile(), Integer.valueOf(RedisTime.MESSAGE_TIME.getName().toString()), code);
            } else {
                throw new Exception("codeType未知类型");
            }
            //记录短信验证码
            smsLogService.insert(new SmsLog() {{
                setCode(code);
                setTelephone(memberRequest.getMobile());
                setStatus("0");
                setCreator(member != null ? member.getId() : 0);
                setCreateTime(new Date());
            }});
            log.info("发送短信====>>>>>" + memberRequest.getMobile());
            return RestResult.success(new MemberRestResponse() {{
                setCode(code);
            }});
        } catch (Exception e) {
            log.error("发送验证码错误==》》》》" + e.getLocalizedMessage());
            return RestResult.error("9999", e.getLocalizedMessage());
        }
    }

    public void checkCode(MemberRequest memberRequest) throws Exception {
        String code = memberRequest.getCode();
        if (StringUtils.isEmpty(code)) {
            throw new Exception("验证码不能为空");
        }
        String recode = null;
        if (memberRequest.getCodeType() == 0) {

            recode = redisClientTemplate.get(RedisKey.LOGIN_MESSAGE_KEY_.getName() + memberRequest.getMobile());
        } else if (memberRequest.getCodeType() == 1) {
            recode = redisClientTemplate.get(RedisKey.CHECK_MOBILE_MESSAGE_KEY_.getName() + memberRequest.getMobile());
        } else if (memberRequest.getCodeType() == 2) {
            recode = redisClientTemplate.get(RedisKey.UPDATE_PASSWORD_MESSAGE_KEY_.getName() + memberRequest.getMobile());
        } else if (memberRequest.getCodeType() == 3) {
            recode = redisClientTemplate.get(RedisKey.UPDATE_MOBILE_MESSAGE_KEY_.getName() + memberRequest.getMobile());
        }
//        if (StringUtils.isEmpty(recode)) {
//            throw new Exception("验证码已失效,请重新获取");
//        }
//        if (!recode.equalsIgnoreCase(code)) {
//            throw new Exception("验证码不正确,请重新输入");
//        }
    }

    /*
     * 修改绑定的手机号
     * */
    @ApiOperation("修改绑定的手机号")
    @ResponseBody
    @PostMapping("updateMemberMobileByToken")
    public RestResult<String> updateMemberMobileByToken(@RequestBody MemberRequest memberRequest) {
        try {
            String token = memberRequest.getToken();
            String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + token);
            if (StringUtils.isEmpty(memStr)) {
                return RestResult.error("4000", "登录失效");
            }
            //判断验证码是否正确
            checkCode(new MemberRequest() {{
                setMobile(memberRequest.getMobile());
                setCodeType(memberRequest.getCodeType());
                setCode(memberRequest.getCode());
            }});
            Member member = JSONArray.parseObject(memStr, Member.class);
            MememberUser mememberUser = mememberUserService.queryByPrimaryKey(member.getId());
            Integer status = mememberUser.getStatus();
            if (status == 0) {
                return RestResult.error("9999", "当前账号已注销");
            }
            //修改手机号码
            mememberUserService.update(new MememberUser() {{
                setId(member.getId());
                setPhone(memberRequest.getMobile());
            }});
            return RestResult.success("修改成功");
        } catch (Exception e) {
            log.error("修改手机号错误====>>>>" + e.getLocalizedMessage());
            return RestResult.error("9999", e.getLocalizedMessage());
        }
    }

    /*
     * 校验手机号
     * */
    @ApiOperation("校验短信验证码")
    @ResponseBody
    @PostMapping("checkMemberMobileByToken")
    public RestResult<String> checkMemberMobileByToken(@RequestBody MemberRequest memberRequest) {
        try {
            String token = memberRequest.getToken();
            String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + token);
            if (StringUtils.isEmpty(memStr)) {
                return RestResult.error("4000", "登录失效");
            }
            Member member = JSONArray.parseObject(memStr, Member.class);
            MememberUser mememberUser = mememberUserService.queryByPrimaryKey(member.getId());
            Integer status = mememberUser.getStatus();
            if (status == 0) {
                return RestResult.error("9999", "当前账号已注销");
            }
            //判断验证码是否正确
            checkCode(new MemberRequest() {{
                setMobile(mememberUser.getPhone());
                setCodeType(memberRequest.getCodeType());
                setCode(memberRequest.getCode());
            }});
            return RestResult.success("校验成功");
        } catch (Exception e) {
            log.error("校验成功手机号错误====>>>>" + e.getLocalizedMessage());
            return RestResult.error("9999", e.getLocalizedMessage());
        }
    }

    @ApiOperation("修改登录密码")
    @ResponseBody
    @PostMapping("updateMemberPassWordByToken")
    public RestResult<String> updateMemberPassWordByToken(@RequestBody UpdateMemberPassWordByTokenRequest merReq) {
        try {
            if (merReq.getSettingPassword() && StringUtils.isEmpty(merReq.getOldPassword())) {
                return RestResult.error("9999", "原密码不可为空");
            }
            if (StringUtils.isEmpty(merReq.getNewPassword())) {
                return RestResult.error("9999", "新密码不可为空");
            }
            if (StringUtils.isEmpty(merReq.getConfirmPassword())) {
                return RestResult.error("9999", "确认密码不可为空");
            }
            if (!merReq.getConfirmPassword().equals(merReq.getNewPassword())) {
                return RestResult.error("9999", "两次密码输入不一致");
            }
            String token = merReq.getToken();
            String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + token);
            if (StringUtils.isEmpty(memStr)) {
                return RestResult.error("4000", "登录失效");
            }
            Member member = JSONArray.parseObject(memStr, Member.class);
            MememberUser mememberUser = mememberUserService.queryByPrimaryKey(member.getId());
            Integer status = mememberUser.getStatus();
            if (status == 0) {
                return RestResult.error("9999", "当前账号已注销");
            }
            if (merReq.getSettingPassword() && !MD5Utils.verify(merReq.getOldPassword(), mememberUser.getSalt(), mememberUser.getPassword())) {
                return RestResult.error("9999", "原密码输入有误");
            }
            if (!merReq.getSettingPassword()) {
                mememberUser.setSalt(UUID.randomUUID().toString());
            }
            MememberUser update = new MememberUser();
            update.setId(mememberUser.getId());
            update.setSalt(mememberUser.getSalt());
            update.setPassword(MD5Utils.md5(merReq.getNewPassword(), mememberUser.getSalt()));
            mememberUserService.update(update);
            redisClientTemplate.del(RedisKey.H5_LOGIN_TOKEN_.getName() + token);
            return RestResult.success("登录密码修改成功");
        } catch (Exception e) {
            log.error("修改登录密码失败==============>>>" + e.getLocalizedMessage());
            return RestResult.error("9999", e.getLocalizedMessage());
        }
    }

}
